package com.jinlia.show.common.core.utils;

import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class MybatisIdGenerator implements IdentifierGenerator {
    private final Long workerIdBits = 5L;
    private final Long datacenterIdBits = 5L;

    private final Long twepoch; // 起始时间戳
    private final Long workerId; // 工作机器ID
    private final Long datacenterId; // 数据中心ID

    private long sequence = 0L;
    private long lastTimestamp = -1L;

    @Override
    public Long nextId(Object entity) {
        // 返回生成的ID值
        return this.nextId(); // 调用分布式ID生成逻辑
    }


    /**
     * @param epoch        起始时间戳
     * @param workerId     工作机器ID
     * @param datacenterId 数据中心ID
     */
    public MybatisIdGenerator(Long epoch, Long workerId, Long datacenterId) {
        long maxWorkerId = ~(-1L << workerIdBits); // = 31
        long maxDatacenterId = ~(-1L << datacenterIdBits);// =31
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(
                    String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(
                    String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
        }
        this.twepoch = epoch;
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    /**
     * 获取下一个ID
     *
     * @return ID
     */
    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }
        long sequenceBits = 12L;
        if (lastTimestamp == timestamp) {
            long sequenceMask = ~(-1L << sequenceBits);
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = timestamp & 1L;
        }
        lastTimestamp = timestamp;
        long datacenterIdShift = sequenceBits + workerIdBits;
        long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
        System.out.println("数据中心值为" + (datacenterId << datacenterIdShift));
        return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << sequenceBits) | sequence;
    }

    //从ID中逆运算获取数据中心ID的方法
    public static long extractDatacenterId2(long id) {
        long datacenterIdBits = 5l;
        long datacenterIdMask = ~(-1L << datacenterIdBits); // 创建一个掩码，用于保留数据中心ID的位
        long  datacenterIdShift = 12l + datacenterIdBits;
        return (id >> datacenterIdShift) & datacenterIdMask;
    }

    /**
     * 获取时间戳
     *
     * @param lastTimestamp 最后时间撮
     * @return 时间戳
     */
    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    /**
     * 生成时间戳
     *
     * @return 时间戳
     */
    protected long timeGen() {
        return System.currentTimeMillis();
    }


    private static final long SEQUENCE_BITS = 12L;       // 序列号位数
    private static final long WORKER_ID_BITS = 2L;       // 工作机器ID位数
    private static final long DATACENTER_ID_BITS = 1L;   // 数据中心ID位数

    // 左移位数（需与生成逻辑一致）
    private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;
    private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
    private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;

    // 最大取值范围掩码
    private static final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BITS);    // 4095
    private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);  // 31
    private static final long MAX_DATACENTER_ID = ~(-1L << DATACENTER_ID_BITS); // 31
    public static long extractTimestamp(long id, long twepoch) {
        return (id >> TIMESTAMP_LEFT_SHIFT) + twepoch;
    }
    /**
     * 从ID解析数据中心ID
     */
    public static long extractDatacenterId(long id) {
        return (id >> DATACENTER_ID_SHIFT) & MAX_DATACENTER_ID;
    }
    /**
     * 从ID解析工作机器ID
     */
    public static long extractWorkerId(long id) {
        return (id >> WORKER_ID_SHIFT) & MAX_WORKER_ID;
    }
    /**
     * 从ID解析序列号
     */
    public static long extractSequence(long id) {
        return id & MAX_SEQUENCE;
    }
    /**
     * 从ID逆向解析所有信息
     * @return Map<String, Long> 包含时间戳、数据中心ID、工作机器ID、序列号
     */
    public static Map<String, Long> parseId(long id, long twepoch) {
        Map<String, Long> result = new HashMap<>();
        result.put("timestamp", extractTimestamp(id, twepoch));  // 原始时间戳（需结合twepoch计算实际时间）
        result.put("datacenterId", extractDatacenterId(id));
        result.put("workerId", extractWorkerId(id));
        result.put("sequence", extractSequence(id));
        return result;
    }
    public static void main(String[] args) {
        // 初始化生成器（参数需与生成时一致）
//        MybatisIdGenerator generator = new MybatisIdGenerator(1288834974657L, 2l, 2l);
//
//        // 生成一个ID
//        long id = generator.nextId();
//        System.out.println("生成的ID: " + id);

        // 逆向解析
        Map<String, Long> parsed = MybatisIdGenerator.parseId(1929350788147093505l, 1288834974657L);
        System.out.println("解析结果: " + parsed);

        // 打印人类可读时间
        System.out.println("生成时间: " + new Date(parsed.get("timestamp")));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(new Date(parsed.get("timestamp")));
        System.out.println(formattedDate);
        System.out.println(System.currentTimeMillis());
    }
}
